<?php

namespace app\admin\controller;

use controller\BasicAdmin;
use service\DataService;
use think\Db;
use think\exception\HttpResponseException;
use think\facade\App;

/**
 * 代理商管理控制器
 * Class User
 * @package app\community\controller
 * @author zoudingyong <sheyingtg@qq.com>
 * @date 2018/11/7 13:12
 */
class Agent extends BasicAdmin
{

    /**
     * 指定当前数据表
     * @var string
     */
    public $agent = 'jixie_agent';
    public $agent_level = 'jixie_agent_level';
    public $member = 'jixie_member';

    /**
     * 列表
     * @return array|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\Exception
     */
    public function lists()
    {
        $this->title = '代理商列表';
        $get = $this->request->get();
        $db = Db::name($this->agent)
            ->alias('a')
            ->join($this->agent_level . ' b', 'b.level_id=a.level_id', 'left')
            ->field('a.*,b.level_name');

        foreach (['agent_id', 'name', 'mobile'] as $key) {
            (isset($get[$key]) && $get[$key] !== '') && $db->whereLike($key, "%{$get[$key]}%");
        }
        if (isset($get['date']) && $get['date'] !== '') {
            list($start, $end) = explode(' - ', $get['date']);
            $db->whereBetween('create_at', ["{$start} 00:00:00", "{$end} 23:59:59"]);
        }
        return parent::_list($db->order('agent_id desc'));
    }

    /**
     * 操作
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\Exception
     */
    public function operate()
    {
        if (!$this->request->isPost()) {
            $agent_id = $this->request->get('id');
            $agent = Db::name($this->agent)->find($agent_id);
            empty($agent) && $this->error('未找到相关代理商！');
            $this->_form_assign();
            return $this->fetch('form', ['vo' => $agent, 'title' => '操作']);
        }
        try {
            $agent_id = $this->request->post('id');
            $agent = Db::name($this->agent)->find($agent_id);
            empty($agent) && $this->error('未找到相关代理商！');

            $data = [
                'status' => $this->request->post('status'),
                'level_id' => $this->request->post('level_id'),
                'examine_at' => date('Y-m-d H:i:s', time()),
                'remark' => $this->request->post('remark'),
            ];

            Db::transaction(function () use ($data, $agent_id) {
                $where = ['agent_id' => $agent_id];
                Db::name($this->agent)->where($where)->update($data);

                //自动生成二维码
                $newAgent = Db::name($this->agent)->find($agent_id);
                if (empty($newAgent['ewm_url']) && $newAgent['status'] == 1) {
                    $this->makeCode($agent_id);
                }
            });

        } catch (HttpResponseException $exception) {
            return $exception->getResponse();
        } catch (\Exception $e) {
            $this->error('操作失败，请稍候再试！' . $e->getMessage());
        }
        $this->success('操作成功！', "");
    }

    public function makeCode($agent_id)
    {
        $agent = Db::name($this->agent)->find($agent_id);
        empty($agent) && $this->error('未找到相关代理商！');
        $agent['status'] !== 1 && $this->error('代理商未通过审核！');
        $agent['is_deleted'] == 1 && $this->error('代理商被取消了资格！');

        $config = [
            'appid' => config('wechat.wxapp_appid'),
            'appsecret' => config('wechat.wxapp_appsecret'),
        ];

        $we = new \WeMini\Qrcode($config);
//            $path = 'pages/purchase/purchase?agent_id=' . $agent_id;
        $page = 'pages/index/index';
        $result = $we->createMiniScene($agent_id, $page, $width = 430);

//            $result = $we->createDefault($path);
        $file_url = request()->root(true) . '/static/upload/qcode/';
        $bytes = file_put_contents(App::getRootPath() . 'static/upload/qcode/' . $agent_id . '.jpg', $result);
        if ($bytes > 0) {
            $ewm_url = $file_url . $agent_id . '.jpg';
        } else {
            $ewm_url = '';
        }
        $data = [
            'ewm_url' => $ewm_url,
        ];

        Db::transaction(function () use ($data, $agent_id, $agent) {
            $where = ['agent_id' => $agent_id];
            Db::name($this->agent)->where($where)->update($data);

        });
    }

    /**
     * 生成二维码
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\Exception
     */
    public function makeCode2()
    {
        try {
            $agent_id = $this->request->post('id');
            $agent = Db::name($this->agent)->find($agent_id);
            empty($agent) && $this->error('未找到相关代理商！');
            $agent['status'] !== 1 && $this->error('代理商未通过审核！');
            $agent['is_deleted'] == 1 && $this->error('代理商被取消了资格！');

            $config = [
                'appid' => config('wechat.wxapp_appid'),
                'appsecret' => config('wechat.wxapp_appsecret'),
            ];

            $we = new \WeMini\Qrcode($config);
//            $path = 'pages/purchase/purchase?agent_id=' . $agent_id;
            $page = 'pages/index/index';
            $result = $we->createMiniScene($agent_id, $page, $width = 430);

//            $result = $we->createDefault($path);
            $file_url = request()->root(true) . '/static/upload/qcode/';
            $bytes = file_put_contents(App::getRootPath() . 'static/upload/qcode/' . $agent_id . '.jpg', $result);
            if ($bytes > 0) {
                $ewm_url = $file_url . $agent_id . '.jpg';
            } else {
                $ewm_url = '';
            }
            $data = [
                'ewm_url' => $ewm_url,
            ];

            Db::transaction(function () use ($data, $agent_id, $agent) {
                $where = ['agent_id' => $agent_id];
                Db::name($this->agent)->where($where)->update($data);

            });

        } catch (HttpResponseException $exception) {
            return $exception->getResponse();
        } catch (\Exception $e) {
            $this->error('操作失败，请稍候再试！' . $e->getMessage());
        }
        $this->success('操作成功！', "");
    }

    /**
     * 表单数据处理
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function _form_assign()
    {
        list($where, $order) = [[], 'sort desc'];
        $level = (array)Db::name($this->agent_level)->where($where)->order($order)->select();
        $this->assign([
            'level' => $level,
        ]);
    }

    /**
     * 恢复代理商
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function recover()
    {
        if (DataService::update($this->agent)) {
            $this->success("恢复成功！", '');
        }
        $this->error("恢复失败，请稍候再试！");
    }

    /**
     * 取消代理商
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function del()
    {
        $agent_id = $this->request->post('id');
        if (DataService::update($this->agent)) {

            //取消之前代理商的客户
            $where = ['agent_id' => $agent_id];
            Db::name($this->member)->where($where)->update(['agent_id' => 0]);

            $this->success("取消成功！", '');
        }
        $this->error("取消失败，请稍候再试！");
    }
}
